﻿using AutoMapper;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Caching.Memory;
using S7.Net;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Zocono.Infrastructure.Common;
using Zocono.WCS.Admin.Models.ConfigManager;
using Zocono.WCS.Admin.Models.User;
using Zocono.WCS.Application.AppConfigureManage;
using Zocono.WCS.Application.AppTraces;
using Zocono.WCS.Domain.EntityInfo;
using Zocono.WCS.Infrastructure.ApllicationDto.DtoWcsManage;
using Zocono.WCS.Infrastructure.ApllicationDto.WCSTaskDto;

namespace Zocono.WCS.Admin.Controllers.ConfigManageMoudle
{
    public class PlcConnectionInfoController : BaseController
    {
        private readonly PlcConnectionInfoApp _plcConnectionInfoApp;

        public PlcConnectionInfoController(PlcConnectionInfoApp plcConnectionInfoApp, IMemoryCache memoryCache, TracesApp tracesApp, IHttpContextAccessor httpContextAccessor) : base(memoryCache, tracesApp, httpContextAccessor)
        {
            this._plcConnectionInfoApp = plcConnectionInfoApp;
        }

        public IActionResult Index()
        {
            return View();
        }
        /// <summary>
        /// PLC连接列表页
        /// </summary>
        /// <returns></returns>
        public  ActionResult PlcConnectionInfoAsync()
        {
            var pageModel = new PlcConnectionInfoFliterPageData();
            pageModel.IsScItems = IsScItem.IsScItemDatasource;
            pageModel.S7CpuTypes = S7CpuTypeItem.S7CpuTypeDatasource;
            //await AddTracesInfo();
            return View(pageModel);
        }

        /// <summary>
        /// 获取所有的连接列表数据
        /// </summary>
        /// <returns></returns>
        public async Task<JsonResult> GetAllPlcConnectionInfoAsync()
        {
            var where = new QueryPlcConnectionInfoDto();
            where.PageIndex = (Start / Length) + 1;
            where.PageSize = Length;
            where.Ip = Request.Form["ip"].ToString();
            var cpuType = Request.Form["cpuType"].ToInt32();
            if (cpuType != -1)
            {
                where.CpuType = Request.Form["cpuType"].ToInt32();
            }
            var isScStr = Request.Form["issc"].ToString();
            if (isScStr != "-1")
            {
                where.IsSc = Request.Form["issc"].ToBool();
            }
            where.ScEquipmentCode = Request.Form["scCode"].ToString();
            var plcConList = await _plcConnectionInfoApp.GetPagedPlcConnectionInfoAsync(where);
            //var plcConListDto = _mapper.Map<List<PlcConnectionInfo>, List<PlcConnectionInfoDto>>(plcConList.Result);
            var plcConDtoList = new List<PlcConnectionInfoDto>();
            foreach (var plcCon in plcConList.Result)
            {
                plcConDtoList.Add(new PlcConnectionInfoDto
                {
                    ID = plcCon.ID,
                    IP = plcCon.IP,
                    PlcCpuType = plcCon.PlcCpuType.ToInt32(),
                    Rack = plcCon.Rack,
                    Slot = plcCon.Slot,
                    IsSc = plcCon.IsSc,
                    ScEquipmentCode = plcCon.ScEquipmentCode,
                }) ;
            }
            var pageData = new TableData<PlcConnectionInfoDto>(Draw, plcConList.Total, plcConList.Total, plcConDtoList);

            //await AddTracesInfo(5, 0, "获取PLC连接列表");
            return Json(pageData);
        }
        /// <summary>
        /// 添加或者编辑页面
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<ActionResult> PlcConnectInfoAddOrEditAsync(long id)
        {
            var pageData = new PlcConnectionInfoPageData();
            pageData.IsScItems = IsScItem.IsScItemDatasource;
            pageData.S7CpuTypes = S7CpuTypeItem.S7CpuTypeDatasource;
            pageData.PlcCpuType = -1;
            if (id > 0)
            {
                var plcConInfo = await _plcConnectionInfoApp.GetPlcConnectionInfoByIdAsync(id);
                pageData.IP = plcConInfo.IP;
                pageData.ID = plcConInfo.ID;
                pageData.PlcCpuType = plcConInfo.PlcCpuType.ToInt32();
                pageData.Rack = plcConInfo.Rack;
                pageData.Slot = plcConInfo.Slot;
                pageData.IsSc = plcConInfo.IsSc;
                pageData.ScEquipmentCode = plcConInfo.ScEquipmentCode;
            }

            return View(pageData);
        }

        /// <summary>
        /// 添加或者编辑操作
        /// </summary>
        /// <returns></returns>
        public async Task<JsonResult> OperatePlcConnectInfoAsync()
        {
            var plcConInfo = new PlcConnectionInfo();
            plcConInfo.ID = Request.Form["id"].ToInt64();
            plcConInfo.IP = Request.Form["ip"].ToString();
            plcConInfo.PlcCpuType = (CpuType)(Enum.Parse(typeof(CpuType), Request.Form["cpuType"].ToInt32() + "") as Enum);
            plcConInfo.Rack = (short)Request.Form["rack"].ToInt32();
            plcConInfo.Slot = (short)Request.Form["slot"].ToInt32();
            plcConInfo.IsSc = Request.Form["isSc"].ToInt32().Equals(1);
            plcConInfo.ScEquipmentCode = Request.Form["scCode"].ToString();
            bool result;
            string msg;
            try
            {
                if (plcConInfo.ID == 0)
                {
                    result = await _plcConnectionInfoApp.CreatePlcConnectionInfoAsync(plcConInfo);
                    await AddTracesInfo(2, 0, "新增PLC连接配置");
                }
                else
                {
                    result = await _plcConnectionInfoApp.ModifyPlcConnectionInfoAsync(plcConInfo);
                    await AddTracesInfo(3, 0, "修改PLC连接配置");
                }
                msg = result ? "成功" : "失败";
            }
            catch (Exception e)
            {
                result = false;
                msg = e.Message;
            }
            return CreateJsonGetResult(result, msg);
        }

        /// <summary>
        /// 通过ID删除连接配置
        /// </summary>
        /// <returns></returns>
        public async Task<JsonResult> DeletePlcConnetInfoAsync()
        {
            var id = Request.Form["id"].ToInt64();
            bool result;
            string msg;
            try
            {
                result = await _plcConnectionInfoApp.DeletePlcConnectionInfoByIdAsync(id);
                msg = result ? "成功" : "失败";
            }
            catch (Exception e)
            {
                result = false;
                msg = e.Message;
            }
            await AddTracesInfo(4, 0, "删除PLC连接配置");
            return CreateJsonGetResult(result, msg);
        }
        /// <summary>
        /// PLC连接状态也没
        /// </summary>
        /// <returns></returns>
        public  ActionResult PlcConnectionStateInfoAsync()
        {
            //await AddTracesInfo();

            return View();
        }
        /// <summary>
        /// 获取PLC连接状态数据
        /// </summary>
        /// <returns></returns>
        public async Task<JsonResult> GetAllPlcConnectStateInfoAsync()
        {
            var where = new QueryPlcConnectionStateInfoDto();
            where.ProgrameCode = Request.Form["ProgrameCode"].ToString();

            var plcStates = await _plcConnectionInfoApp.GetPlcConnectionStateInfoAsync(where);

            var plcStatePageDatas = new List<PlcConnectionStateInfoPageData>();
            if (plcStates != null && plcStates.Count > 0)
            {
                foreach (var item in plcStates)
                {
                    plcStatePageDatas.Add(new PlcConnectionStateInfoPageData()
                    {
                        ID = item.ID,
                        PlcConnectionID = item.PlcConnectionID,
                        ProgrameCode = item.ProgrameCode,
                        Connected = item.Connected,
                        UpdateTime = item.UpdateTime,
                        PlcConnectionIP = item.PlcConnectionIP,
                        PlcCpuType = item.PlcCpuType,
                    });
                }
            }

            var pageData = new TableData<PlcConnectionStateInfoPageData>(Draw, plcStates.Count, plcStates.Count, plcStatePageDatas);
            //await AddTracesInfo(5, 0, "获取PLC连接状态列表");
            return Json(pageData);
        }


        /// <summary>
        /// PLC连接锁定也没
        /// </summary>
        /// <returns></returns>
        public  ActionResult PlcConnectionLockInfoAsync()
        {
            //await AddTracesInfo();

            return View();
        }
        /// <summary>
        /// 获取PLC连接锁定数据
        /// </summary>
        /// <returns></returns>
        public async Task<JsonResult> GetAllPlcConnectLockInfoAsync()
        {
            var where = new QueryPlcConnectionLockInfoDto();
            where.ProgrameCode = Request.Form["ProgrameCode"].ToString();
            where.JobName = Request.Form["JobName"].ToString();

            var plcLocks = await _plcConnectionInfoApp.GetPlcConnectionLockInfoAsync(where);

            var plcLockPageDatas = new List<PlcConnectionLockInfoPageData>();
            if (plcLocks != null && plcLocks.Count > 0)
            {
                foreach (var item in plcLocks)
                {
                    plcLockPageDatas.Add(new PlcConnectionLockInfoPageData()
                    {
                        ID = item.ID,
                        PlcConnectionID = item.PlcConnectionID,
                        ProgrameCode = item.ProgrameCode,
                        IsLock = item.IsLock,
                        UpdateTime = item.UpdateTime,
                        PlcConnectionIP = item.PlcConnectionIP,
                        PlcCpuType = item.PlcCpuType,
                        JobName = item.JobName,
                    });
                }
            }

            var pageData = new TableData<PlcConnectionLockInfoPageData>(Draw, plcLocks.Count, plcLocks.Count, plcLockPageDatas);
            //await AddTracesInfo(5, 0, "获取PLC连接锁定列表");
            return Json(pageData);
        }
    }
}
